import { ipcMain, app, shell, dialog } from 'electron';
import { isDev } from '../utils/env.js';

// 设置IPC处理程序
export function setupIpcHandlers(mainWindow) {
  // 窗口控制
  ipcMain.handle('window-minimize', () => {
    if (mainWindow) {
      mainWindow.minimize();
    }
  });

  ipcMain.handle('window-maximize', () => {
    if (mainWindow) {
      if (mainWindow.isMaximized()) {
        mainWindow.unmaximize();
      } else {
        mainWindow.maximize();
      }
    }
  });

  ipcMain.handle('window-close', () => {
    if (mainWindow) {
      mainWindow.close();
    }
  });

  ipcMain.handle('quit-app', () => {
    app.quit();
  });

  ipcMain.handle('get-window-state', () => {
    if (mainWindow) {
      return {
        isMaximized: mainWindow.isMaximized(),
        isMinimized: mainWindow.isMinimized(),
        isFullScreen: mainWindow.isFullScreen()
      };
    }
    return null;
  });

  // 开发者工具控制
  ipcMain.handle('toggle-devtools', () => {
    if (mainWindow) {
      if (mainWindow.webContents.isDevToolsOpened()) {
        mainWindow.webContents.closeDevTools();
      } else {
        mainWindow.webContents.openDevTools();
      }
    }
  });

  ipcMain.handle('open-devtools', () => {
    if (mainWindow) {
      mainWindow.webContents.openDevTools();
    }
  });

  ipcMain.handle('is-devtools-opened', () => {
    if (mainWindow) {
      return mainWindow.webContents.isDevToolsOpened();
    }
    return false;
  });

  ipcMain.handle('close-devtools', () => {
    if (mainWindow) {
      mainWindow.webContents.closeDevTools();
    }
  });

  // 外部链接
  ipcMain.handle('open-external', (event, url) => {
    shell.openExternal(url);
  });

  // 应用信息
  ipcMain.handle('get-app-version', () => {
    return app.getVersion();
  });

  // 环境信息
  ipcMain.handle('is-dev', () => {
    return isDev;
  });

  ipcMain.on('is-dev', (event) => {
    event.returnValue = isDev;
  });

  // 文件和目录选择
  ipcMain.handle('select-file', async (event, options) => {
    if (!mainWindow) return null;
    
    const result = await dialog.showOpenDialog(mainWindow, {
      properties: ['openFile'],
      ...options
    });
    
    return result.canceled ? null : result.filePaths[0];
  });

  ipcMain.handle('select-directory', async () => {
    if (!mainWindow) return null;
    
    const result = await dialog.showOpenDialog(mainWindow, {
      properties: ['openDirectory']
    });
    
    return result.canceled ? null : result.filePaths[0];
  });

  // 日志写入
  ipcMain.on('write-log', (event, message) => {
    console.log('[Renderer]', message);
  });
}